package cn.rdtimes.wolfdsp.core.job;

import cn.rdtimes.wolfdsp.core.counter.PrefCounter;

import java.io.PrintStream;

/**
 * 对整体调度流程的计数器
 *
 * @author BZ
 */
class ScheduleCounters {
    private final static int PREF_COUNT = 3;
    private final PrefCounter[] prefCounters;

    ScheduleCounters() {
        prefCounters = new PrefCounter[PREF_COUNT];
        init();
    }

    private void init() {
        for (CounterKind kind : CounterKind.values()) {
            prefCounters[kind.getId()] = PrefCounter.makePrefCounter(kind.getName());
        }
    }

    PrefCounter getPrefCounter(CounterKind kind) {
        return prefCounters[kind.getId()];
    }

    PrefCounter[] getPrefCounter() {
        return prefCounters;
    }

    void dumpPrintStream(PrintStream pw) {
        for (int i = 0; i < prefCounters.length; i++) {
            pw.print(prefCounters[i]);
            if (i != (prefCounters.length - 1)) pw.print(",");
        }
    }

    PrefCounter addCounter(CounterKind kind, long value) {
        PrefCounter counter = getPrefCounter(kind);
        if (counter != null) counter.add(value);
        return counter;
    }

    long getCount(CounterKind kind, long defaultValue) {
        PrefCounter counter = getPrefCounter(kind);
        if (counter != null) return counter.get();
        return defaultValue;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(128);
        for (int i = 0; i < prefCounters.length; i++) {
            sb.append(prefCounters[i]);
            if (i != (prefCounters.length - 1)) sb.append(",");
        }
        return sb.toString();
    }

    enum CounterKind {
        // 完成调度数量
        COMPLETED(0, "CompletedCounts"),
        // 异常调度数量
        EXCEPTION(1, "ExceptionCounts"),
        // kill调度数量
        KILL(2, "KillCounts"),
        ;

        private int id;
        private String name;

        CounterKind(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }
    }

}
